package org.oep.jmingle;

class SimpleRecord {

    private final static int ADDRESS_INDEX = 0;
    private final static int NAME_INDEX = 12;
    private final static int TIME_INDEX = 44;
    private final static int ADDRESS_LEN = 12;
    private final static int NAME_LEN = 32;
    private final static int TIME_LEN = 19;
    private final static int MAX_REC_LEN = 63;

    private static StringBuffer recBuf =
        new StringBuffer(MAX_REC_LEN);

    // Don't let anyone instantiate this class
    private SimpleRecord() {}

    // Clear internal buffer
    private static void clearBuf() {
        for (int i = 0; i < MAX_REC_LEN; i++) {
            recBuf.insert(i, ' ');
        }
        recBuf.setLength(MAX_REC_LEN);
    }

    /**
     * Takes component parts and return a record suitable
     * for our address book.
     *
     *  return  byte[] the newly created record
     *  address - device address
     *  name - device name
     */
    public static byte[] createRecord(String address,
                                      String name, long time) {
        clearBuf();
        String str_time = String.valueOf(time);
        recBuf.insert(ADDRESS_INDEX, address);
        recBuf.insert(NAME_INDEX, name);
        recBuf.insert(TIME_INDEX, str_time);
        recBuf.setLength(MAX_REC_LEN);
        return recBuf.toString().getBytes();
    }

    /**
     * Extracts the address field from a record.
     *  return  String contains the address
     *  b       the record to parse
     */
    public static String getAddress(byte[] b) {
        return new String(b, ADDRESS_INDEX, ADDRESS_LEN).trim();
    }


    /**
     * Extracts the phone number field from a record.
     *  return  String contains the name field
     *  b       the record to parse
     */
    public static String getName(byte[] b) {
        return new String(b, NAME_INDEX, NAME_LEN).trim();
    }
    
    public static long getTime(byte[] b) {
    	String t = new String(b, TIME_INDEX, TIME_LEN).trim();
    	return Long.parseLong(t);
    }
}